package org.adream.account.util;

import javax.servlet.http.HttpServletRequest;

import org.adream.account.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.util.StringUtils;

/**
 * TCP/IP工具
 * @author 沈宇鑫
 *
 */
public class TCPIPUtils {
	
	private final static Logger logger = LoggerFactory.getLogger(TCPIPUtils.class);
	
	private final static String UNKNOWN = "unknown";

	/** 
	 * 获取访问用户真实ip相关属性
	 * @param rq 用户访问请求
	 * @return 真实ip地址
	 */
	public static String getClientIp(HttpServletRequest rq) {
		String ip;
		ip = rq.getHeader("x-forwarded-for");
		if(!isEmpty(ip)) {
			//多次反向代理返回第一个ip
			return ip.split(",")[0];
		}
		ip = rq.getHeader("Proxy-Client-IP");
		if(!isEmpty(ip)) {
			return ip.split(",")[0];
		}
		ip = rq.getHeader("WL-Proxy-Client-IP");
		if(!isEmpty(ip)) {
			return ip.split(",")[0];
		}
		ip = rq.getHeader("HTTP-CLIENT-IP");
		if(!isEmpty(ip)) {
			return ip.split(",")[0];
		}
		ip = rq.getHeader("HTTP_X_FORWARDED_FOR");
		if(!isEmpty(ip)) {
			return ip.split(",")[0];
		}
		ip = rq.getHeader("X-Real-IP");
		if(!isEmpty(ip)) {
			return ip.split(",")[0];
		}
		ip = rq.getRemoteAddr();
		return ip;
	}
	
	/**
	 * 获取访问用户真实ip相关属性
	 * 安全隐患：用户伪造请求头，所以记录所有信息
	 * @param rq 用户访问请求
	 * @return 真实ip地址相关属性
	 */
	public static String getClientIpInfo(HttpServletRequest rq) throws Exception{
		StringBuffer ipInfo= new StringBuffer();
		String ip;
		ip = rq.getHeader("x-forwarded-for");
		if(!isEmpty(ip)) {
			ipInfo.append("x-forwarded-for");
			ipInfo.append(ip);
		}
		ip = rq.getHeader("Proxy-Client-IP");
		if(!isEmpty(ip)) {
			ipInfo.append("Proxy-Client-IP");
			ipInfo.append(ip);
		}
		ip = rq.getHeader("WL-Proxy-Client-IP");
		if(!isEmpty(ip)) {
			ipInfo.append("WL-Proxy-Client-IP");
			ipInfo.append(ip);
		}
		ip = rq.getHeader("HTTP-CLIENT-IP");
		if(!isEmpty(ip)) {
			ipInfo.append("HTTP-CLIENT-IP");
			ipInfo.append(ip);
		}
		ip = rq.getHeader("HTTP_X_FORWARDED_FOR");
		if(!isEmpty(ip)) {
			ipInfo.append("HTTP_X_FORWARDED_FOR");
			ipInfo.append(ip);
		}
		ip = rq.getHeader("X-Real-IP");
		if(!isEmpty(ip)) {
			ipInfo.append("X-Real-IP");
			ipInfo.append(ip);
		}
		ip = rq.getRemoteAddr();
		ipInfo.append("remote-addr");
		ipInfo.append(ip);
		if(ipInfo.length() > 255) {
			logger.error("超长的IPinfo");
			logger.error(ipInfo.toString());
			throw new Exception("跳转太多，有攻击倾向，请禁止访问");
		}
		return ipInfo.toString();
	}
	
	//判断是否为空ip
	private static boolean isEmpty(String ip) {
		return ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip);
	}
	
	//方法测试
	public static void main(String []args) {
		System.out.println("222".split(",")[0]);

		System.out.println("".split(",")[0]);
	}
}